Contents | Index | < Browse | Browse >

LETTERfgetcULETTER Reads a character from a file.

Overview
#include <stdio.h>

c = fgetc(fp)

int c; // character read
FILE *fp; // file pointer

Portability
ANSI

Description
"fgetc" reads a character from the file pointed to by "fp" and converts it at first to "unsigned char" and then to "int" - as you might know there is no clear differenciation between numbers and chars.

Returns
If the end of the file has been reached or any other error occured "EOF" is returned.

See also
fopen , fputc , getc , getchar , ungetc

Example
#include <string.h>
#include <stdio.h>

void main(void)
{
FILE *fp;
char string[] = "This is a test", ch;

if((fp = fopen("DUMMY.File","w+")) == NULL)
{ printf("Error opening file\n");
exit(0);
}

// Writes the string into the file
if(fwrite(string, strlen(string), 1, fp) == NULL)
{ printf("Error writing to file\n");
exit(0);
}

// Position file pointer at the beginning of the file
fseek(fp, 0, SEEK_SET);
do { ch = fgetc(fp); // reads a character from the file
putchar(ch); // output character
}
while(ch != EOF);
fclose(fp);
}